// pages/vipRecharge/vipRecharge.js
var app = getApp();
const getPageInfoUrl = '/Recharge/index';
const payForVipUrl = '/Recharge/goPayVip';
const getQrCodeImgUrl = '/RechangeQrCode/getQrCode';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    displayAuthShow: 0,//控制授权弹层的显示和隐藏
    recharge_title_limit_title:'',//底部盒子标题
    recharge_equity_list:'',//按钮底部列表文案
    isAdding: false, //判断用户是否正在点击加入会员
    isLoading: 1, //是否显示加载中图标
    isWithdrawalsSuccessShow: 0, //控制充值成功弹层的显示
    uid: 0, //分享者的ID
    shareImg: '', //分享的图片
    sharePath: '', //分享的路径
    shareTitle: '', //分享的标题
    winWidth: 0, //手机屏幕的宽度
    winHeight: 0, //手机屏幕的高度
    isQRCodeMaskShow: 0, //控制分享二维码弹层的显示
    isShareMaskShow: 0, //控制分享的弹层显示
    QRCodeImg: '', //二维码图片地址
    QRCodeImgHttp: '', //http二维码图片地址
    isUseHttp: 0, //判断是否使用http
    localSourceUri: '', //存储静态资源地址
    sys_status: 0, //控制是否为审核态
    adv_solt: {}, //悬浮广告数据
    recharge_no_vip_one_title: '', //页面顶部第一行标题（非会员）
    recharge_vip_one_title: '', //页面顶部第一行标题（会员）
    recharge_no_vip_two_title: '', //页面顶部第二行标题（非会员）
    recharge_vip_two_title: '', //页面顶部第二行标题（会员）
    recharge_no_vip_equity_title: '', //会员权益图片列表标题（非VIP)
    recharge_vip_equity_title: '', //会员权益图片列表标题（VIP)
    recharge_no_vip_pay_title: '', //底部按钮文字（普通用户）
    recharge_no_vip_fens_pay_title: '', //底部按钮文字（粉丝）
    recharge_vip_invite_title: '', //底部按钮文字（会员）
    vip_desc_configs: [], //会员权益描述数组
    vip_icon_configs: [], //会员权益图片列表
    user_balance: 0.00, //用户的余额
    cash_num: 0.00, //现金券余额
    user_level: 0, //用户的身份
    token: '', //用户的唯一标识
  },
  // 关闭充值成功弹层
  withdrawalsCloseBtn: function() {
    var _this = this;
    _this.setData({
      isWithdrawalsSuccessShow: 0
    })
  },
  goCouponList: function() {
    wx.navigateTo({
      url: '/pages/couponList/couponList',
    })
  },
  goHome: function() {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  // 阻止点击事件
  preventEvent: function() {},
  // 点击邀请会员按钮
  sendWelfare: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    this.setData({
      isShareMaskShow: 1
    })
  },
  // 关闭弹层
  closeMask: function() {
    this.setData({
      isShareMaskShow: 0
    })
  },
  // 支付会员
  payForVip: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.setData({
      isAdding: true
    })
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type
    }
    app.post(payForVipUrl, requestData, function(res) {
      if (res.code == 2000) {
        wx.hideLoading();
        var payInfo = res.data;
        if (payInfo.respay) {
          wx.requestPayment({
            'timeStamp': payInfo.respay.timeStamp,
            'nonceStr': payInfo.respay.nonceStr,
            'package': payInfo.respay.package,
            'signType': 'MD5',
            'paySign': payInfo.respay.paySign,
            'success': function(res) {
              // _this.getPageInfo();
              _this.setData({
                isWithdrawalsSuccessShow: 1,
                isAdding: true
              })
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 1500
              })
            },
            'fail': function(res) {
              // _this.getPageInfo();
              _this.setData({
                isAdding: false
              })
            },
            'complete': function(res) {
              _this.getPageInfo();
            }
          });
        } else {
          _this.getPageInfo();
          _this.setData({
            isAdding: true,
            isWithdrawalsSuccessShow: 1
          })
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
        }

      } else {
        _this.setData({
          isAdding: false
        })
        wx.hideLoading();
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
    });
  },
  // 获取页面信息
  getPageInfo: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      uid: _this.data.uid
    }
    app.post(getPageInfoUrl, requestData, function(res) {
      if (res.code == 2000) {
        var vip_icon_configs = res.data.vip_icon_configs;
        var vip_icon_configs = res.data.vip_icon_configs;
        var configs = wx.getStorageSync('configs');
        for (var i = 0; i < vip_icon_configs.length; i++) {
          vip_icon_configs[i].image = configs.static_url_http + '/' + vip_icon_configs[i].image;
        }
        var user_level = res.data.level;
        _this.setData({
          isLoading: 0,
          recharge_title_limit_title: res.data.recharge_title_limit_title,
          recharge_equity_list: res.data.recharge_equity_list,
          adv_solt: res.data.adv,
          cash_num: res.data.cash_num,
          user_balance: res.data.amount,
          user_level: user_level,
          recharge_no_vip_equity_title: res.data.recharge_no_vip_equity_title,
          recharge_no_vip_fens_pay_title: res.data.recharge_no_vip_fens_pay_title,
          recharge_no_vip_pay_title: res.data.recharge_no_vip_pay_title,
          recharge_no_vip_one_title: res.data.recharge_no_vip_one_title,
          recharge_no_vip_two_title: res.data.recharge_no_vip_two_title,
          recharge_vip_equity_title: res.data.recharge_vip_equity_title,
          recharge_vip_invite_title: res.data.recharge_vip_invite_title,
          recharge_vip_one_title: res.data.recharge_vip_one_title,
          recharge_vip_two_title: res.data.recharge_vip_two_title,
          vip_desc_configs: res.data.vip_desc_configs,
          vip_icon_configs: res.data.vip_icon_configs,
        })
        if (user_level == 3 || user_level == 4 || user_level == 5) {
          _this.setData({
            shareImg: res.data.share.image,
            sharePath: res.data.share.page,
            shareTitle: res.data.share.title
          });
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 获取二维码
  getQrCodeImg: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type
    }
    app.post(getQrCodeImgUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          QRCodeImg: res.data.image,
          QRCodeImgHttp: res.data.image_http
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 点击获取生成二维码按钮
  gerQrcode: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.getQrCodeImg();
    _this.setData({
      isQRCodeMaskShow: 1,
      isShareMaskShow: 0
    })
  },
  // 保存图片
  saveImg: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    console.log(e);
    wx.downloadFile({
      url: _this.data.QRCodeImg,
      success: function(res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            console.log(res)
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            console.log(res)
            console.log('fail')
          }
        })
      },
      fail: function() {
        console.log('fail')
      }
    })
  },
  // 预览图片
  previewImg: function() {
    var _this = this;
    var urls;
    if (_this.data.isUseHttp == 1) {
      urls = [_this.data.QRCodeImgHttp]
    } else {
      urls = [_this.data.QRCodeImg]
    }
    wx.previewImage({
      current: _this.data.QRCodeImg, // 当前显示图片的http链接
      urls: urls
    })
  },
  // 关闭分享二维码弹层
  closeQRCodeMask: function() {
    this.setData({
      isQRCodeMaskShow: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    var configs = wx.getStorageSync('configs');
    if (options.uid && options.uid != 'undefined') {
      _this.setData({
        uid: options.uid
      })
    };
    if (!options.uid || options.uid == 'undefined') {
      _this.setData({
        uid: 0
      })
    }
    var scene = decodeURIComponent(options.scene);
    if (scene && scene !== 'undefined') {
      _this.setData({
        uid: scene
      })
    }

    _this.setData({
      sys_status: configs.sys_status,
      localSourceUri: configs.static_url_http
    })
    wx.getSystemInfo({
      success: function(res) {
        if (res.system.search('iOS') == -1) {
          _this.setData({
            isUseHttp: 1
          })
        } else {
          _this.setData({
            isUseHttp: 0
          })
        }
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        })
      }
    });
    app.checkAuthioze(success => {
      _this.loop();
    }, fail => {
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getPageInfo();

    }
  },
  /*角色权限控制*/
  getUserInfo: function (e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function () {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow: 0,
          isfriendShareMaskShow: 1,
          cash: cash
        })
      }
      that.loop();
    });
  },
  authRest: function () {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function () {
      wx.reLaunch({
        url: '/pages/bargain/bargain',
      })
    }, 1000)
  },
  /*红包广告跳转事件*/
  goAdvEvent: function(e) {
    var _this = this;
    var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {}
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var _this = this;
    _this.setData({
      isShareMaskShow: 0
    });
    return {
      title: _this.data.shareTitle,
      path: _this.data.sharePath,
      imageUrl: _this.data.shareImg
    }
  }
})